/* eslint-disable no-console */
/* eslint-disable no-param-reassign */
/* eslint-disable @typescript-eslint/no-non-null-asserted-optional-chain */
/* eslint-disable @typescript-eslint/no-shadow */
/* eslint-disable react-hooks/rules-of-hooks */
import type { ConnectState } from '@/models/connect';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import React, { useState ,useRef} from 'react';
import type { CurrentUser, Dispatch } from 'umi';
import { connect } from 'umi';
import type { GetSellerParamsType,sellerExportParams } from '@/services/seller';
import { getSeller ,sellerDataToCsvApi} from '@/services/seller';
import { Avatar, Card, Descriptions, Tooltip,Button,message,Spin } from 'antd';
import UpdateForm from './components/UpdateForm';
import { AlignCenterOutlined } from '@ant-design/icons';
import UseRate from './components/UseRate';

interface SellerProps {
  dispatch: Dispatch;
  userState?: CurrentUser;
}

interface SellerItemValue {
  id: string;
  name: string; // 商户名称
  picture: string; // 图片
  amount: string;
  brokerage: string; // 分润
  profit: string; // 收益
  pb_7day_use_rate: string; // 充电宝7天使用率
  pl_7day_use_rate: string; // 充电线7天使用率
  create_time: string; // 创建时间
  pb_num: string; // 充电宝数量
  pl_num: string; // 充电线数量
  billingtime: number; // 计时单位
  billingunit: number; // 计时格式
  ceiling: number; // 封顶
}

// 商户管理
const sellerList: React.FC<SellerProps> = (props) => {
  const { userState } = props;
  const [loading,setLoading]  = useState(false) // 是否加载中
  const [page, setPage] = useState(1); // 设置页数
  const [limit, setLimit] = useState(10); // 设置数据读取数
  const [sellerNum, setSellerNum] = useState(0); // 设置商家数量
  const [select, setSelect] = useState(''); // 搜索商户
  const [having, setHaving] = useState(''); // 是否铺货
  const [sid, setSid] = useState('');

  const [aid, setAid] = useState(''); // 代理Id
  const [aname, setAname] = useState(''); // 代理名称
  const [orderBy, setOrderBy] = useState<number | string>(''); // 商户排序

  const [totalBalance, setTotalBalance] = useState(0); // 总余额
  const [subtotalBalance, setSubtotalBalance] = useState(0); // 本页总计
  const [showForm, setShowForm] = useState(false); // 处理表单显示

  const ref = useRef<ActionType>();

  const [useRateShow, setUseRateShow] = useState(false); // 使用率统计
  const [selectSeller, setSelectSeller] = useState<string>(); // 选择的商户

  const updateFormShow = (show: boolean) => {
    // 处理表单的显示
    if (show) {
      setShowForm(true);
    } else {
      // 隐藏
      setShowForm(false);
    }
  };

  // 表格配置
  let columns: ProColumns<SellerItemValue>[] = [
    {
      dataIndex: 'id',
      title: '商户Id',
      fixed: showForm ? false : 'left',
      copyable: true,
    },
    {
      dataIndex: 'name',
      title: '商户名称',
      fixed: showForm ? false : 'left',
    },
    {
      dataIndex: 'phone',
      title: '商户手机',
      search: false,
    },
    {
      dataIndex: 'addr',
      title: '商户地址',
      fixed: 'left',
    },
    {
      dataIndex: 'aid',
      title: '代理Id',
      hideInTable: true,
    },
    {
      dataIndex: 'aname',
      title: '代理名称',
      hideInTable: true,
    },
    {
      dataIndex: 'balance',
      title: '余额',
      valueType: 'money',
      search: false,
    },
    {
      dataIndex: 'brokerage',
      title: '分润比例',
      search: false,
      valueType: 'percent',
    },
    {
      dataIndex: 'is_hava_device',
      title: '是否铺货',
      valueEnum: {
        0: { text: '全部' },
        true: { text: '已铺货', status: 'Success' },
        false: { text: '未铺货', status: 'Error' },
      },
    },
    {
      dataIndex: 'create_time',
      title: '注册时间',
      valueType: 'dateTime',
    },
    {
      dataIndex: 'order_by',
      title: '商户排序',
      valueEnum: {
        0: { text: '创建时间' },
        1: { text: '宝使用率从高到低' },
        2: { text: '宝使用率从低到高' },
        3: { text: '线使用率从高到低' },
        4: { text: '线使用率从低到高' },
      },
      hideInTable: true,
    },
    {
      dataIndex: 'pb_num',
      title: '机柜数量',
      search: false,
      render: (_, row) => {
        return (
          <Tooltip title={row.pb_num} key={row.id}>
            <Avatar style={{ backgroundColor: '#87d068' }}>{row.pb_num}</Avatar>
          </Tooltip>
        );
      },
    },
    {
      dataIndex: 'pb_7day_use_rate',
      title: '机柜使用率',
      valueType: 'percent',
      search: false,
    },
    {
      dataIndex: 'pl_num',
      title: '充电线数量',
      search: false,
      render: (_, row) => {
        return (
          <Tooltip title={row.pl_num} key={row.id}>
            <Avatar style={{ color: '#f56a00', backgroundColor: '#fde3cf' }}>{row.pl_num}</Avatar>
          </Tooltip>
        );
      },
    },
    {
      dataIndex: 'pl_7day_use_rate',
      title: '充电线使用率',
      valueType: 'percent',
      search: false,
    },
    {
      dataIndex: 'profit',
      title: '收益',
      valueType: 'money',
      search: false,
    },
  ];

  // 判断代理等级是不是大于店铺代理
  if (
    props.userState &&
    props.userState.type &&
    (props.userState.type === 5 || props.userState.type < 5)
  ) {
    columns = columns.concat([
      {
        title: '店铺管理ID',
        search: false,
        dataIndex: 'said',
        copyable: true,
      },
      {
        title: '店铺管理名称',
        search: false,
        dataIndex: 'sname',
      },
    ]);
  }
  // 判断代理等级是不是大于等于业务代理
  if (
    props.userState &&
    props.userState.type &&
    props.userState.type !== 5 &&
    props.userState.type >= 1
  ) {
    columns = columns.concat([
      {
        title: '业务代理ID',
        search: false,
        dataIndex: 'baid',
        copyable: true,
      },
      {
        title: '业务代理名称',
        search: false,
        dataIndex: 'bname',
      },
    ]);
  }
  // 判断代理等级是不是大于等于区域经理
  if (
    props.userState &&
    props.userState.type &&
    props.userState.type !== 5 &&
    props.userState.type >= 2
  ) {
    columns = columns.concat([
      {
        title: '区域经理ID',
        search: false,
        dataIndex: 'aaid',
        copyable: true,
      },
      {
        title: '区域经理名称',
        search: false,
        dataIndex: 'aname',
      },
    ]);
  }
  // 判断代理等级是不是大于等于市级经理
  if (
    props.userState &&
    props.userState.type &&
    props.userState.type !== 5 &&
    props.userState.type >= 3
  ) {
    columns = columns.concat([
      {
        title: '市级代理ID',
        search: false,
        dataIndex: 'caid',
        copyable: true,
      },
      {
        title: '市级代理名称',
        search: false,
        dataIndex: 'cname',
      },
    ]);
  }
  // 判断代理等级是不是大于等于省级经理
  if (
    props.userState &&
    props.userState.type &&
    props.userState.type !== 5 &&
    props.userState.type === 4
  ) {
    columns = columns.concat([
      {
        title: '省级代理ID',
        search: false,
        dataIndex: 'paid',
        copyable: true,
      },
      {
        title: '省级代理名称',
        search: false,
        dataIndex: 'pname',
      },
    ]);
  }

  // 固定操作栏
  columns.push({
    title: '操作',
    key: 'option',
    fixed: showForm ? false : 'right',
    valueType: 'option',
    render: (_, row) => [
      // <UpdateForm
      //   key={row.id}
      //   sellerId={row.id}
      //   updateFormShow={(show: boolean) => updateFormShow(show)}
      //   updateEvent={() => ref.current?.reload()}
      // ></UpdateForm>,
      // 使用率统计
      <Button
        key={row.id}
        type="primary"
        onClick={() => {
          setSelectSeller(row.id);
          setUseRateShow(true);
          updateFormShow(true);
        }}
      >
        <AlignCenterOutlined />
        使用率
      </Button>,
    ],
  });

  return (
    <PageContainer>
      <Spin spinning={loading} tip="导出中...">
      <ProTable
        headerTitle="商户管理"
        scroll={{ x: 'max-content' }}
        rowKey={(columns) => columns.id}
        actionRef={ref}
        search={{
          defaultCollapsed: false,
        }}
        onReset={() => {
          setPage(1);
        }}
        tableExtraRender={() => (
          <Card>
            <Descriptions size="small" bordered={true}>
              <Descriptions.Item label="商户余额总计">{totalBalance}</Descriptions.Item>
              <Descriptions.Item label="每页余额总计">{subtotalBalance}</Descriptions.Item>
            </Descriptions>
          </Card>
          )}
          // 工具栏
        toolBarRender={() => [
          <Button
            onClick={async () => {
              try {
                const data: sellerExportParams = {
                    uId: Number(userState?.id!),
                    userType: Number(userState?.user_type!),
                    token: userState?.token!,
                    select,
                    aname,
                    is_hava_device:having,
                    order_by:0,
                    aid,
                    
                };
                setLoading(true);
                const res = await sellerDataToCsvApi(data);
                if (res.code === 0) {
                  const newUrl = await (await fetch(res.data)).arrayBuffer() // 将返回数据转成buff对象
                  const nowTime = new Date().toLocaleString()
                  const fileName = `${nowTime}商户列表.csv`;
                  const myBlob = new Blob([newUrl], {type: 'text/csv,charset=UTF-8'});
                  const link = document.createElement("a");
                  link.href = URL.createObjectURL(myBlob);
                  link.download = fileName;
                  link.click();
                  link.remove();
                  URL.revokeObjectURL(link.href);
                  setLoading(false);
                  message.success('导出成功');
                  } else {
                    message.error(res.msg);
                }
                
              } catch (error) {
                console.log(error)
              }
          }}
          >
            导出
          </Button>,
        ]}
        request={async () => {
          const data: GetSellerParamsType = {
            uId: userState?.id!,
            userType: userState?.user_type!,
            token: userState?.token!,
            select,
            sid,
            aid,
            aname,
            is_hava_device: having,
            page,
            limit,
            order_by: orderBy,
          };
          return getSeller(data);
        }}
        postData={(res) => {
          //   console.log('【获取商户数据】', res);
          setSellerNum((res as any).seller_num);
          setTotalBalance((res as any).total_balance);
          setSubtotalBalance((res as any).subtotal_balance);
          (res as any).seller.map((item: any) => {
            item.sname = item?.sagency?.name;
            item.bname = item?.bagency?.name;
            item.aname = item?.aagency?.name;
            item.cname = item?.cagency?.name;
            item.pname = item?.pagency?.name;
            return item;
          });
          return (res as any).seller;
        }}
        beforeSearchSubmit={(params: any) => {
          console.log(params);
          // 查找
          if (params.name) {
            setSelect(params.name);
          } else {
            setSelect('');
          }
          if (params.is_hava_device === 'false') {
            setHaving('2');
          } else if (params.is_hava_device === 'true') {
            setHaving('1');
          } else if (params.is_hava_device === 0) {
            setHaving('');
          }
          // 商户id
          if (params.id) {
            setSid(params.id);
          } else {
            setSid('');
          }
          // 代理id
          if (params.aid) {
            setAid(params.aid);
          } else {
            setAid('');
          }
          // 代理名称
          if (params.aname) {
            setAname(params.aname);
          } else {
            setAname('');
          }
          // 排序
          if (params.order_by === -1) {
            setOrderBy('');
          } else {
            setOrderBy(Number(params.order_by));
          }
          return params;
        }}
        pagination={{
          pageSize: limit,
          total: sellerNum,
          onChange: (page) => {
            setPage(page);
          },
          onShowSizeChange: (_, size) => {
            setLimit(size);
          },
        }}
        columns={columns}
        ></ProTable>
        </Spin>
      <UseRate
        visible={useRateShow}
        onCancel={() => {
          setUseRateShow(false);
          updateFormShow(false);
          setSelectSeller('');
        }}
        uId={userState?.id!}
        userType={userState?.user_type!}
        token={userState?.token!}
        sid={selectSeller ?? ''}
      ></UseRate>
    </PageContainer>
  );
};

export default connect(({ user }: ConnectState) => ({ userState: user.currentUser }))(sellerList);
